home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-02 / comp-pas.zip / TUTORPAS.ZIP / TUTOR12.DOC < prev    next >
Text File  |  1989-06-05  |  34KB  |  926 lines

  1. OPA A
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.                             LET'S BUILD A COMPILER!
  30.  
  31.                                        By
  32.  
  33.                             Jack W. Crenshaw, Ph.D.
  34.  
  35.                                   5 June 1989
  36.  
  37.  
  38.                               Part XII: MISCELLANY
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67. PA A
  68.  
  69.  
  70.  
  71.  
  72.  
  73.        *****************************************************************
  74.        *                                                               *
  75.        *                        COPYRIGHT NOTICE                       *
  76.        *                                                               *
  77.        *   Copyright (C) 1989 Jack W. Crenshaw. All rights reserved.   *
  78.        *                                                               *
  79.        *****************************************************************
  80.  
  81.  
  82.        INTRODUCTION
  83.  
  84.        This installment is another one  of  those  excursions  into side
  85.        alleys  that  don't  seem to fit  into  the  mainstream  of  this
  86.        tutorial  series.    As I mentioned last time, it was while I was
  87.        writing this installment that I realized some changes  had  to be
  88.        made  to  the  compiler structure.  So I had to digress from this
  89.        digression long enough to develop the new structure  and  show it
  90.        to you.
  91.  
  92.        Now that that's behind us, I can tell you what I  set  out  to in
  93.        the first place.  This shouldn't  take  long, and then we can get
  94.        back into the mainstream.
  95.  
  96.        Several people have asked  me  about  things that other languages
  97.        provide, but so far I haven't addressed in this series.   The two
  98.        biggies are semicolons and  comments.    Perhaps  you've wondered
  99.        about them, too, and  wondered  how things would change if we had
  100.        to  deal with them.  Just so you can proceed with what's to come,
  101.        without being  bothered by that nagging feeling that something is
  102.        missing, we'll address such issues here.
  103.  
  104.  
  105.        SEMICOLONS
  106.  
  107.        Ever since the introduction of Algol, semicolons have been a part
  108.        of  almost every modern language.  We've all  used  them  to  the
  109.        point that they are taken for  granted.   Yet I suspect that more
  110.        compilation errors have  occurred  due  to  misplaced  or missing
  111.        semicolons  than  any  other single cause.  And if we had a penny
  112.        for  every  extra  keystroke programmers have used  to  type  the
  113.        little rascals, we could pay off the national debt.
  114.  
  115.        Having  been  brought  up with FORTRAN, it took me a long time to
  116.        get used to using semicolons, and to tell the  truth  I've  never
  117.        quite understood why they  were  necessary.    Since I program in
  118.        Pascal, and since the use of semicolons in Pascal is particularly
  119.        tricky,  that one little character is still  by  far  my  biggest
  120.        source of errors.
  121.  
  122.        When  I  began  developing  KISS,  I resolved to  question  EVERY
  123.        construct in other languages, and to try to avoid the most common
  124.        problems that occur with them.  That puts the semicolon very high
  125.        on my hit list.A6A6
  126.                                      - 2 -A*A*
  127. PA A
  128.  
  129.  
  130.  
  131.  
  132.  
  133.        To  understand  the  role of the semicolon, you have to look at a
  134.        little history.
  135.  
  136.        Early programming languages were line-oriented.  In  FORTRAN, for
  137.        example, various parts  of  the statement had specific columns or
  138.        fields that they had to appear in.  Since  some  statements  were
  139.        too  long for one line, the  "continuation  card"  mechanism  was
  140.        provided to let  the  compiler  know  that a given card was still
  141.        part of the previous  line.   The mechanism survives to this day,
  142.        even though punched cards are now things of the distant past.
  143.  
  144.        When  other  languages  came  along,  they  also  adopted various
  145.        mechanisms for dealing with multiple-line statements.  BASIC is a
  146.        good  example.  It's important to  recognize,  though,  that  the
  147.        FORTRAN  mechanism  was   not   so  much  required  by  the  line
  148.        orientation of that  language,  as by the column-orientation.  In
  149.        those versions of FORTRAN  where  free-form  input  is permitted,
  150.        it's no longer needed.
  151.  
  152.        When the fathers  of  Algol introduced that language, they wanted
  153.        to get away  from  line-oriented programs like FORTRAN and BASIC,
  154.        and allow for free-form input.   This included the possibility of
  155.        stringing multiple statements on a single line, as in
  156.  
  157.  
  158.             a=b; c=d; e=e+1;
  159.  
  160.  
  161.        In cases like this,  the  semicolon is almost REQUIRED.  The same
  162.        line, without the semicolons, just looks "funny":
  163.  
  164.  
  165.             a=b c= d e=e+1
  166.  
  167.        I suspect that this is the major ... perhaps ONLY ...  reason for
  168.        semicolons: to keep programs from looking funny.
  169.  
  170.        But  the  idea  of stringing multiple statements  together  on  a
  171.        single  line  is  a  dubious  one  at  best.  It's not very  good
  172.        programming  style,  and  harks back to  the  days  when  it  was
  173.        considered improtant to conserve cards.  In these  days  of CRT's
  174.        and indented code, the clarity of programs is  far  better served
  175.        by  keeping statements separate.  It's still  nice  to  have  the
  176.        OPTION  of  multiple  statements,  but  it seems a shame to  keep
  177.        programmers  in  slavery  to the semicolon, just to keep that one
  178.        rare case from "looking funny."
  179.  
  180.        When I started in with KISS, I tried  to  keep  an  open mind.  I
  181.        decided that I would use  semicolons when it became necessary for
  182.        the parser, but not until then.  I figured this would happen just
  183.        about  the time I added the ability  to  spread  statements  over
  184.        multiple lines.  But, as you  can  see, that never happened.  The
  185.        TINY compiler is perfectly  happy  to  parse the most complicated
  186.        statement, spread over any number of lines, without semicolons.A*A*
  187.                                      - 3 -
  188. PA A
  189.  
  190.  
  191.  
  192.  
  193.  
  194.        Still, there are people  who  have  used  semicolons for so long,
  195.        they feel naked  without them.  I'm one of them.  Once I had KISS
  196.        defined sufficiently well, I began to write a few sample programs
  197.        in the language.    I  discovered,  somewhat to my horror, that I
  198.        kept  putting  semicolons  in anyway.   So  now  I'm  facing  the
  199.        prospect of a NEW  rash  of  compiler  errors, caused by UNWANTED
  200.        semicolons.  Phooey!
  201.  
  202.        Perhaps more to the point, there are readers out  there  who  are
  203.        designing their own languages, which may  include  semicolons, or
  204.        who  want to use the techniques of  these  tutorials  to  compile
  205.        conventional languages like  C.    In  either case, we need to be
  206.        able to deal with semicolons.
  207.  
  208.  
  209.        SYNTACTIC SUGAR
  210.  
  211.        This whole discussion brings  up  the  issue of "syntactic sugar"
  212.        ... constructs that are added to a language, not because they are
  213.        needed, but because they help make the programs look right to the
  214.        programmer.    After  all, it's nice  to  have  a  small,  simple
  215.        compiler,    but  it  would  be  of  little  use if the resulting
  216.        language  were  cryptic  and hard to program.  The language FORTH
  217.        comes  to mind (a premature OUCH! for the  barrage  I  know  that
  218.        one's going to fetch me).  If we can add features to the language
  219.        that  make the programs easier to read  and  understand,  and  if
  220.        those features  help keep the programmer from making errors, then
  221.        we should do so.    Particularly if the constructs don't add much
  222.        to the complexity of the language or its compiler.
  223.  
  224.        The  semicolon  could  be considered an example,  but  there  are
  225.        plenty of others, such as the 'THEN' in a IF-statement,  the 'DO'
  226.        in a WHILE-statement,  and  even the 'PROGRAM' statement, which I
  227.        came within a gnat's eyelash of leaving out  of  TINY.    None of
  228.        these tokens  add  much  to  the  syntax  of the language ... the
  229.        compiler can figure out  what's  going on without them.  But some
  230.        folks feel that they  DO  add to the readability of programs, and
  231.        that can be very important.
  232.  
  233.        There are two schools of thought on this subject, which  are well
  234.        represented by two of our most popular languages, C and Pascal.
  235.  
  236.        To  the minimalists, all such sugar should be  left  out.    They
  237.        argue that it clutters up the language and adds to the  number of
  238.        keystrokes  programmers  must type.   Perhaps  more  importantly,
  239.        every extra token or keyword represents a trap laying in wait for
  240.        the inattentive programmer.  If you leave out  a  token, misplace
  241.        it, or misspell it, the compiler  will  get you.  So these people
  242.        argue that the best approach is to get rid of such things.  These
  243.        folks tend to like C, which has a minimum of unnecessary keywords
  244.        and punctuation.
  245.  
  246.        Those from the other school tend to like Pascal.  They argue that
  247.        having to type a few extra characters is a small price to pay forA*A*
  248.                                      - 4 -
  249. PA A
  250.  
  251.  
  252.  
  253.  
  254.  
  255.        legibility.    After  all, humans have to read the programs, too.
  256.        Their best argument is that each such construct is an opportunity
  257.        to tell the compiler that you really mean for it  to  do what you
  258.        said to.  The sugary tokens serve as useful landmarks to help you
  259.        find your way.
  260.  
  261.        The differences are well represented by the two  languages.   The
  262.        most oft-heard complaint about  C  is  that  it is too forgiving.
  263.        When you make a mistake in C, the  erroneous  code  is  too often
  264.        another  legal  C  construct.    So  the  compiler  just  happily
  265.        continues to compile, and  leaves  you  to  find the error during
  266.        debug.    I guess that's why debuggers  are  so  popular  with  C
  267.        programmers.
  268.  
  269.        On the  other  hand,  if  a  Pascal  program compiles, you can be
  270.        pretty  sure that the program will do what you told it.  If there
  271.        is an error at run time, it's probably a design error.
  272.  
  273.        The  best  example  of  useful  sugar  is  the semicolon  itself.
  274.        Consider the code fragment:
  275.  
  276.  
  277.             a=1+(2*b+c)   b...
  278.  
  279.  
  280.        Since there is no operator connecting the token 'b' with the rest
  281.        of the  statement, the compiler will conclude that the expression
  282.        ends  with  the  ')', and the 'b'  is  the  beginning  of  a  new
  283.        statement.    But  suppose  I  have simply left out the  intended
  284.        operator, and I really want to say:
  285.  
  286.  
  287.             a=1+(2*b+c)*b...
  288.  
  289.  
  290.        In  this  case  the compiler will get an error, all right, but it
  291.        won't be very meaningful  since  it will be expecting an '=' sign
  292.        after the 'b' that really shouldn't be there.
  293.  
  294.        If, on the other hand, I include a semicolon after the  'b', THEN
  295.        there  can  be no doubt where I  intend  the  statement  to  end.
  296.        Syntactic  sugar,  then,  can  serve  a  very  useful purpose  by
  297.        providing some additional insurance that we remain on track.
  298.  
  299.        I find  myself  somewhere  in  the middle of all this.  I tend to
  300.        favor the Pascal-ers' view ... I'd much rather find  my  bugs  at
  301.        compile time rather than run time.  But I also hate to just throw
  302.        verbosity  in  for  no apparent reason, as in COBOL.  So far I've
  303.        consistently left most of the Pascal sugar out of KISS/TINY.  But
  304.        I certainly have no strong feelings either way, and  I  also  can
  305.        see the value of sprinkling a little sugar around  just  for  the
  306.        extra  insurance  that  it  brings.    If  you like  this  latter
  307.        approach, things like that are easy to add.  Just  remember that,A6A6
  308.                                      - 5 -A*A*
  309. PA A
  310.  
  311.  
  312.  
  313.  
  314.  
  315.        like  the semicolon, each item of sugar  is  something  that  can
  316.        potentially cause a compile error by its omission.
  317.  
  318.  
  319.        DEALING WITH SEMICOLONS
  320.  
  321.        There  are  two  distinct  ways  in which semicolons are used  in
  322.        popular  languages.    In Pascal, the semicolon is regarded as an
  323.        statement SEPARATOR.  No semicolon  is  required  after  the last
  324.        statement in a block.  The syntax is:
  325.  
  326.  
  327.             <block> ::= <statement> ( ';' <statement>)*
  328.  
  329.             <statement> ::= <assignment> | <if> | <while> ... | null
  330.  
  331.  
  332.        (The null statement is IMPORTANT!)
  333.  
  334.        Pascal  also defines some semicolons in  other  places,  such  as
  335.        after the PROGRAM statement.
  336.  
  337.        In  C  and  Ada, on the other hand, the semicolon is considered a
  338.        statement TERMINATOR,  and  follows  all  statements  (with  some
  339.        embarrassing and confusing  exceptions).   The syntax for this is
  340.        simply:
  341.  
  342.  
  343.             <block> ::= ( <statement> ';')*
  344.  
  345.  
  346.        Of  the two syntaxes, the Pascal one seems on the face of it more
  347.        rational, but experience has shown  that it leads to some strange
  348.        difficulties.  People get  so  used  to  typing a semicolon after
  349.        every  statement  that  they tend to  type  one  after  the  last
  350.        statement in a block, also.  That usually doesn't cause  any harm
  351.        ...  it  just gets treated as a  null  statement.    Many  Pascal
  352.        programmers, including yours truly,  do  just  that. But there is
  353.        one  place you absolutely CANNOT type  a  semicolon,  and  that's
  354.        right before an ELSE.  This little gotcha  has  cost  me  many an
  355.        extra  compilation,  particularly  when  the  ELSE  is  added  to
  356.        existing code.    So  the  C/Ada  choice  turns out to be better.
  357.        Apparently Nicklaus Wirth thinks so, too:  In his  Modula  2,  he
  358.        abandoned the Pascal approach.
  359.  
  360.        Given either of these two syntaxes, it's an easy matter (now that
  361.        we've  reorganized  the  parser!) to add these  features  to  our
  362.        parser.  Let's take the last case first, since it's simpler.
  363.  
  364.        To begin, I've made things easy by introducing a new recognizer:
  365.  
  366.  
  367.        {--------------------------------------------------------------}
  368.        { Match a Semicolon }A*A*
  369.                                      - 6 -
  370. PA A
  371.  
  372.  
  373.  
  374.  
  375.  
  376.        procedure Semi;
  377.        begin
  378.           MatchString(';');
  379.        end;
  380.        {--------------------------------------------------------------}
  381.  
  382.  
  383.        This procedure works very much like our old Match.  It insists on
  384.        finding a semicolon as the next token.  Having found it, it skips
  385.        to the next one.
  386.  
  387.        Since a  semicolon follows a statement, procedure Block is almost
  388.        the only one we need to change:
  389.  
  390.  
  391.        {--------------------------------------------------------------}
  392.        { Parse and Translate a Block of Statements }
  393.  
  394.        procedure Block;
  395.        begin
  396.           Scan;
  397.           while not(Token in ['e', 'l']) do begin
  398.              case Token of
  399.               'i': DoIf;
  400.               'w': DoWhile;
  401.               'R': DoRead;
  402.               'W': DoWrite;
  403.               'x': Assignment;
  404.              end;
  405.              Semi;
  406.              Scan;
  407.           end;
  408.        end;
  409.        {--------------------------------------------------------------}
  410.  
  411.  
  412.        Note carefully the subtle change in the case statement.  The call
  413.        to  Assignment  is now guarded by a test on Token.   This  is  to
  414.        avoid calling Assignment when the  token  is  a  semicolon (which
  415.        could happen if the statement is null).
  416.  
  417.        Since declarations are also  statements,  we  also  need to add a
  418.        call to Semi within procedure TopDecls:
  419.  
  420.  
  421.        {--------------------------------------------------------------}
  422.        { Parse and Translate Global Declarations }
  423.  
  424.        procedure TopDecls;
  425.        begin
  426.           Scan;
  427.           while Token = 'v' do begin
  428.              Alloc;
  429.              while Token = ',' doA*A*
  430.                                      - 7 -
  431. PA A
  432.  
  433.  
  434.  
  435.  
  436.  
  437.                 Alloc;
  438.              Semi;
  439.           end;
  440.        end;
  441.        {--------------------------------------------------------------}
  442.  
  443.  
  444.        Finally, we need one for the PROGRAM statement:
  445.  
  446.  
  447.        {--------------------------------------------------------------}
  448.        { Main Program }
  449.  
  450.        begin
  451.           Init;
  452.           MatchString('PROGRAM');
  453.           Semi;
  454.           Header;
  455.           TopDecls;
  456.           MatchString('BEGIN');
  457.           Prolog;
  458.           Block;
  459.           MatchString('END');
  460.           Epilog;
  461.        end.
  462.        {--------------------------------------------------------------}
  463.  
  464.  
  465.        It's as easy as that.  Try it with a copy of TINY and see how you
  466.        like it.
  467.  
  468.        The Pascal version  is  a  little  trickier,  but  it  still only
  469.        requires  minor  changes,  and those only to procedure Block.  To
  470.        keep things as simple as possible, let's split the procedure into
  471.        two parts.  The following procedure handles just one statement:
  472.  
  473.  
  474.        {--------------------------------------------------------------}
  475.        { Parse and Translate a Single Statement }
  476.  
  477.        procedure Statement;
  478.        begin
  479.           Scan;
  480.           case Token of
  481.            'i': DoIf;
  482.            'w': DoWhile;
  483.            'R': DoRead;
  484.            'W': DoWrite;
  485.            'x': Assignment;
  486.           end;
  487.        end;
  488.        {--------------------------------------------------------------}ABAB
  489.                                      - 8 -A*A*
  490. PA A
  491.  
  492.  
  493.  
  494.  
  495.  
  496.        Using this procedure, we can now rewrite Block like this:
  497.  
  498.  
  499.        {--------------------------------------------------------------}
  500.        { Parse and Translate a Block of Statements }
  501.  
  502.        procedure Block;
  503.        begin
  504.           Statement;
  505.           while Token = ';' do begin
  506.              Next;
  507.              Statement;
  508.           end;
  509.        end;
  510.        {--------------------------------------------------------------}
  511.  
  512.  
  513.        That  sure  didn't  hurt, did it?  We can now parse semicolons in
  514.        Pascal-like fashion.
  515.  
  516.  
  517.        A COMPROMISE
  518.  
  519.        Now that we know how to deal with semicolons, does that mean that
  520.        I'm going to put them in KISS/TINY?  Well, yes and  no.    I like
  521.        the extra sugar and the security that comes with knowing for sure
  522.        where the  ends  of  statements  are.    But I haven't changed my
  523.        dislike for the compilation errors associated with semicolons.
  524.  
  525.        So I have what I think is a nice compromise: Make them OPTIONAL!
  526.  
  527.        Consider the following version of Semi:
  528.  
  529.  
  530.        {--------------------------------------------------------------}
  531.        { Match a Semicolon }
  532.  
  533.        procedure Semi;
  534.        begin
  535.           if Token = ';' then Next;
  536.        end;
  537.        {--------------------------------------------------------------}
  538.  
  539.  
  540.        This procedure will ACCEPT a semicolon whenever it is called, but
  541.        it won't INSIST on one.  That means that when  you  choose to use
  542.        semicolons, the compiler  will  use the extra information to help
  543.        keep itself on track.  But if you omit one (or omit them all) the
  544.        compiler won't complain.  The best of both worlds.
  545.  
  546.        Put this procedure in place in the first version of  your program
  547.        (the  one for C/Ada syntax), and you have  the  makings  of  TINY
  548.        Version 1.2.A6A6
  549.                                      - 9 -A*A*
  550. PA A
  551.  
  552.  
  553.  
  554.  
  555.  
  556.        COMMENTS
  557.  
  558.        Up  until  now  I have carefully avoided the subject of comments.
  559.        You would think that this would be an easy subject ... after all,
  560.        the compiler doesn't have to deal with comments at all; it should
  561.        just ignore them.  Well, sometimes that's true.
  562.  
  563.        Comments can be just about as easy or as difficult as  you choose
  564.        to make them.    At  one  extreme,  we can arrange things so that
  565.        comments  are  intercepted  almost  the  instant  they  enter the
  566.        compiler.  At the  other,  we can treat them as lexical elements.
  567.        Things  tend to get interesting when  you  consider  things  like
  568.        comment delimiters contained in quoted strings.
  569.  
  570.  
  571.        SINGLE-CHARACTER DELIMITERS
  572.  
  573.        Here's an example.  Suppose we assume the  Turbo  Pascal standard
  574.        and use curly braces for comments.  In this case we  have single-
  575.        character delimiters, so our parsing is a little easier.
  576.  
  577.        One  approach  is  to  strip  the  comments  out the  instant  we
  578.        encounter them in the input stream; that is,  right  in procedure
  579.        GetChar.    To  do  this,  first  change  the  name of GetChar to
  580.        something else, say GetCharX.  (For the record, this is  going to
  581.        be a TEMPORARY change, so best not do this with your only copy of
  582.        TINY.  I assume you understand that you should  always  do  these
  583.        experiments with a working copy.)
  584.  
  585.        Now, we're going to need a  procedure  to skip over comments.  So
  586.        key in the following one:
  587.  
  588.  
  589.        {--------------------------------------------------------------}
  590.        { Skip A Comment Field }
  591.  
  592.        procedure SkipComment;
  593.        begin
  594.           while Look <> '}' do
  595.              GetCharX;
  596.           GetCharX;
  597.        end;
  598.        {--------------------------------------------------------------}
  599.  
  600.  
  601.        Clearly, what this procedure is going to do is to simply read and
  602.        discard characters from the input  stream, until it finds a right
  603.        curly brace.  Then it reads one more character and returns  it in
  604.        Look.
  605.  
  606.        Now we can  write  a  new  version of GetChar that SkipComment to
  607.        strip out comments:ABAB
  608.                                     - 10 -A*A*
  609. PA A
  610.  
  611.  
  612.  
  613.  
  614.  
  615.        {--------------------------------------------------------------}
  616.        { Get Character from Input Stream }
  617.        { Skip Any Comments }
  618.  
  619.        procedure GetChar;
  620.        begin
  621.           GetCharX;
  622.           if Look = '{' then SkipComment;
  623.        end;
  624.        {--------------------------------------------------------------}
  625.  
  626.  
  627.        Code this up  and  give  it  a  try.    You'll find that you can,
  628.        indeed, bury comments anywhere you like.  The comments never even
  629.        get into the parser proper ... every call to GetChar just returns
  630.        any character that's NOT part of a comment.
  631.  
  632.        As a matter of fact, while  this  approach gets the job done, and
  633.        may even be  perfectly  satisfactory  for  you, it does its job a
  634.        little  TOO  well.    First  of all, most  programming  languages
  635.        specify that a comment should be treated like a  space,  so  that
  636.        comments aren't allowed  to  be embedded in, say, variable names.
  637.        This current version doesn't care WHERE you put comments.
  638.  
  639.        Second, since the  rest  of  the  parser can't even receive a '{'
  640.        character, you will not be allowed to put one in a quoted string.
  641.  
  642.        Before you turn up your nose at this simplistic solution, though,
  643.        I should point out  that  as respected a compiler as Turbo Pascal
  644.        also won't allow  a  '{' in a quoted string.  Try it.  And as for
  645.        embedding a comment in an  identifier, I can't imagine why anyone
  646.        would want to do such a  thing,  anyway, so the question is moot.
  647.        For 99% of all  applications,  what I've just shown you will work
  648.        just fine.
  649.  
  650.        But,  if  you  want  to  be  picky  about it  and  stick  to  the
  651.        conventional treatment, then we  need  to  move  the interception
  652.        point downstream a little further.
  653.  
  654.        To  do  this,  first change GetChar back to the way  it  was  and
  655.        change the name called in SkipComment.  Then, let's add  the left
  656.        brace as a possible whitespace character:
  657.  
  658.  
  659.        {--------------------------------------------------------------}
  660.        { Recognize White Space }
  661.  
  662.        function IsWhite(c: char): boolean;
  663.        begin
  664.           IsWhite := c in [' ', TAB, CR, LF, '{'];
  665.        end;
  666.        {--------------------------------------------------------------}ABAB
  667.                                     - 11 -A*A*
  668. PA A
  669.  
  670.  
  671.  
  672.  
  673.  
  674.        Now, we can deal with comments in procedure SkipWhite:
  675.  
  676.  
  677.        {--------------------------------------------------------------}
  678.        { Skip Over Leading White Space }
  679.  
  680.        procedure SkipWhite;
  681.        begin
  682.           while IsWhite(Look) do begin
  683.              if Look = '{' then
  684.                 SkipComment
  685.              else
  686.                 GetChar;
  687.           end;
  688.        end;
  689.        {--------------------------------------------------------------}
  690.  
  691.  
  692.        Note  that SkipWhite is written so that we  will  skip  over  any
  693.        combination of whitespace characters and comments, in one call.
  694.  
  695.        OK, give this one a try, too.   You'll  find  that  it will let a
  696.        comment serve to delimit tokens.  It's worth mentioning that this
  697.        approach also gives us the  ability to handle curly braces within
  698.        quoted strings, since within such  strings we will not be testing
  699.        for or skipping over whitespace.
  700.  
  701.        There's one last  item  to  deal  with:  Nested  comments.   Some
  702.        programmers like the idea  of  nesting  comments, since it allows
  703.        you to comment out code during debugging.  The  code  I've  given
  704.        here won't allow that and, again, neither will Turbo Pascal.
  705.  
  706.        But the fix is incredibly easy.  All  we  need  to  do is to make
  707.        SkipComment recursive:
  708.  
  709.  
  710.        {--------------------------------------------------------------}
  711.        { Skip A Comment Field }
  712.  
  713.        procedure SkipComment;
  714.        begin
  715.           while Look <> '}' do begin
  716.              GetChar;
  717.              if Look = '{' then SkipComment;
  718.           end;
  719.           GetChar;
  720.        end;
  721.        {--------------------------------------------------------------}
  722.  
  723.  
  724.        That does it.  As  sophisticated a comment-handler as you'll ever
  725.        need.ABAB
  726.                                     - 12 -A*A*
  727. PA A
  728.  
  729.  
  730.  
  731.  
  732.  
  733.        MULTI-CHARACTER DELIMITERS
  734.  
  735.        That's all well and  good  for cases where a comment is delimited
  736.        by single  characters,  but  what  about  the  cases such as C or
  737.        standard Pascal, where two  characters  are  required?  Well, the
  738.        principles are still the same, but we have to change our approach
  739.        quite a bit.  I'm sure it won't surprise you to learn that things
  740.        get harder in this case.
  741.  
  742.        For the multi-character situation, the  easiest thing to do is to
  743.        intercept the left delimiter  back  at the GetChar stage.  We can
  744.        "tokenize" it right there, replacing it by a single character.
  745.  
  746.        Let's assume we're using the C delimiters '/*' and '*/'.   First,
  747.        we  need  to  go back to the "GetCharX' approach.  In yet another
  748.        copy of your compiler, rename  GetChar to GetCharX and then enter
  749.        the following new procedure GetChar:
  750.  
  751.  
  752.        {--------------------------------------------------------------}
  753.        { Read New Character.  Intercept '/*' }
  754.  
  755.        procedure GetChar;
  756.        begin
  757.           if TempChar <> ' ' then begin
  758.              Look := TempChar;
  759.              TempChar := ' ';
  760.              end
  761.           else begin
  762.              GetCharX;
  763.              if Look = '/' then begin
  764.                 Read(TempChar);
  765.                 if TempChar = '*' then begin
  766.                    Look := '{';
  767.                    TempChar := ' ';
  768.                 end;
  769.              end;
  770.           end;
  771.        end;
  772.        {--------------------------------------------------------------}
  773.  
  774.  
  775.        As you can see, what this procedure does is  to  intercept  every
  776.        occurrence of '/'.  It then examines the NEXT  character  in  the
  777.        stream.  If the character  is  a  '*',  then  we  have  found the
  778.        beginning  of  a  comment,  and  GetChar  will  return  a  single
  779.        character replacement for it.   (For  simplicity,  I'm  using the
  780.        same '{' character  as I did for Pascal.  If you were writing a C
  781.        compiler, you'd no doubt want to pick some other character that's
  782.        not  used  elsewhere  in C.  Pick anything you like ... even $FF,
  783.        anything that's unique.)
  784.  
  785.        If the character  following  the  '/'  is NOT a '*', then GetChar
  786.        tucks it away in the new global TempChar, and  returns  the  '/'.A*A*
  787.                                     - 13 -
  788. PA A
  789.  
  790.  
  791.  
  792.  
  793.  
  794.        Note that you need to declare this new variable and initialize it
  795.        to ' '.  I like to do  things  like  that  using the Turbo "typed
  796.        constant" construct:
  797.  
  798.  
  799.             const TempChar: char = ' ';
  800.  
  801.  
  802.        Now we need a new version of SkipComment:
  803.  
  804.  
  805.        {--------------------------------------------------------------}
  806.        { Skip A Comment Field }
  807.  
  808.        procedure SkipComment;
  809.        begin
  810.           repeat
  811.              repeat
  812.                 GetCharX;
  813.              until Look = '*';
  814.              GetCharX;
  815.           until Look = '/';
  816.           GetChar;
  817.        end;
  818.        {--------------------------------------------------------------}
  819.  
  820.  
  821.        A  few  things  to  note:  first  of  all, function  IsWhite  and
  822.        procedure SkipWhite  don't  need  to  be  changed,  since GetChar
  823.        returns the '{' token.  If you change that token  character, then
  824.        of  course you also need to change the  character  in  those  two
  825.        routines.
  826.  
  827.        Second, note that  SkipComment  doesn't call GetChar in its loop,
  828.        but  GetCharX.    That  means   that  the  trailing  '/'  is  not
  829.        intercepted and  is seen by SkipComment.  Third, although GetChar
  830.        is the  procedure  doing  the  work,  we  can still deal with the
  831.        comment  characters  embedded  in  a  quoted  string,  by calling
  832.        GetCharX  instead  of  GetChar  while  we're  within  the string.
  833.        Finally,  note  that  we can again provide for nested comments by
  834.        adding a single statement to SkipComment, just as we did before.
  835.  
  836.  
  837.        ONE-SIDED COMMENTS
  838.  
  839.        So far I've shown you  how  to  deal  with  any  kind  of comment
  840.        delimited on the left and the  right.   That only leaves the one-
  841.        sided comments like those in assembler language or  in  Ada, that
  842.        are terminated by the end of the line.  In a  way,  that  case is
  843.        easier.   The only procedure that would need  to  be  changed  is
  844.        SkipComment, which must now terminate at the newline characters:
  845.  
  846.  
  847.        {--------------------------------------------------------------}A*A*
  848.                                     - 14 -
  849. PA A
  850.  
  851.  
  852.  
  853.  
  854.  
  855.        { Skip A Comment Field }
  856.  
  857.        procedure SkipComment;
  858.        begin
  859.           repeat
  860.              GetCharX;
  861.           until Look = CR;
  862.           GetChar;
  863.        end;
  864.        {--------------------------------------------------------------}
  865.  
  866.  
  867.        If the leading character is  a  single  one,  as  in  the  ';' of
  868.        assembly language, then we're essentially done.  If  it's  a two-
  869.        character token, as in the '--'  of  Ada, we need only modify the
  870.        tests  within  GetChar.   Either way, it's an easier problem than
  871.        the balanced case.
  872.  
  873.  
  874.        CONCLUSION
  875.  
  876.        At this point we now have the ability to deal with  both comments
  877.        and semicolons, as well as other kinds of syntactic sugar.   I've
  878.        shown  you several ways to deal with  each,  depending  upon  the
  879.        convention  desired.    The  only  issue left is: which of  these
  880.        conventions should we use in KISS/TINY?
  881.  
  882.        For the reasons that I've given as we went  along,  I'm  choosing
  883.        the following:
  884.  
  885.  
  886.         (1) Semicolons are TERMINATORS, not separators
  887.  
  888.         (2) Semicolons are OPTIONAL
  889.  
  890.         (3) Comments are delimited by curly braces
  891.  
  892.         (4) Comments MAY be nested
  893.  
  894.  
  895.        Put the code corresponding to these cases into your copy of TINY.
  896.        You now have TINY Version 1.2.
  897.  
  898.        Now that we  have  disposed  of  these  sideline  issues,  we can
  899.        finally get back into the mainstream.  In  the  next installment,
  900.        we'll talk  about procedures and parameter passing, and we'll add
  901.        these important features to TINY.  See you then.
  902.  
  903.  
  904.        *****************************************************************
  905.        *                                                               *
  906.        *                        COPYRIGHT NOTICE                       *
  907.        *                                                               *
  908.        *   Copyright (C) 1989 Jack W. Crenshaw. All rights reserved.   *A*A*
  909.                                     - 15 -
  910. PA A
  911.  
  912.  
  913.  
  914.  
  915.  
  916.        *                                                               *
  917.        *****************************************************************AUAU
  918. ASAS
  919.  
  920.  
  921.  
  922.  
  923.  
  924.  
  925.                                     - 16 -A*A*
  926. @